<template>
  <div class="search-suggestion">
    <van-cell v-for="(item,i) in list"  :key="i" icon="search" @click="$emit('search', item)">
        <div slot="title" v-html="highlightText(item)"> </div>
    </van-cell>
  </div>
</template>

<script>
import { getSearch } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false
    }
  },
  computed: {},
  watch: {
    searchText: {
      // 监测的处理函数
      handler: debounce(function (val) { // 防抖处理
        this.onLoadingSearch(val)
      }, 1000),
      // 首次监测触发
      immediate: true
    }
  },
  created () {
    // this.onLoad()
  },
  mounted () {},
  methods: {
    async onLoadingSearch (val) {
    //   console.log(val)
      // 异步更新数据
      try { // 发送联想搜索请求
        const { data } = await getSearch(val)
        // console.log(data)
        this.list = data.data.options
      } catch (err) {
        this.$toast('获取搜索结果失败')
      }
    },
    highlightText (text) {
      // console.log(text)
      if (text) {
        const highlightStr = `<span class="active">${this.searchText}</span>`
        const reg = new RegExp(this.searchText, 'gi') // 正则表达 ==> /输入的内容/gi 全局不区分大小写
        return text.replace(reg, highlightStr) // 替换
      } else {
        return console.log('暂无数据')
      }
    },
    onLoad () {
    }
  }
}
</script>

<style scoped lang="less">
// 深度作用dom改变样式
  /deep/ .van-cell__title{
    span.active{
       color: red !important;
    }
}

</style>
